package com.jdew.thkj.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.RelativeSizeSpan;
import android.util.Log;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.jdew.thkj.R;
import com.jdew.thkj.application.MyApplaction;
import com.jdew.thkj.base.BaseActivity;
import com.jdew.thkj.bean.JDListBean;
import com.jdew.thkj.dialog.CommonDialog;
import com.jdew.thkj.manager.AppConfig;
import com.jdew.thkj.manager.GlideImageLoader;
import com.jdew.thkj.network.RetrofitManager;
import com.jdew.thkj.network.api.RequestApi;
import com.jdew.thkj.utils.CleanCacheUtil;
import com.jdew.thkj.utils.DeviceUtils;
import com.jdew.thkj.utils.MD5Utils;
import com.jdew.thkj.utils.RegexValidateUtils;
import com.jdew.thkj.utils.ToastUtils;
import com.jdew.thkj.utils.WeiboDialogUtils;
import com.kepler.jd.Listener.AsyncInitListener;
import com.kepler.jd.Listener.OpenAppAction;
import com.kepler.jd.login.KeplerApiManager;
import com.kepler.jd.sdk.bean.KeplerAttachParameter;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by yangyang on 2017/9/14.
 */

public class JDProductDetailActivity extends BaseActivity {
    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.name)
    TextView name;
    @Bind(R.id.ymoney)
    TextView ymoney;
    @Bind(R.id.quanhou)
    TextView quanhou;
    @Bind(R.id.salenum)
    TextView salenum;
    @Bind(R.id.share)
    TextView share;
    @Bind(R.id.copy)
    TextView copy;
    @Bind(R.id.money)
    TextView money;
    @Bind(R.id.lianjie)
    TextView lianjie;
    @Bind(R.id.ptitle)
    TextView ptitle;
    @Bind(R.id.banner)
    Banner banner;
    @Bind(R.id.paste)
    TextView paste;
    @Bind(R.id.save)
    TextView save;
    @Bind(R.id.quan)
    TextView quan;
    @Bind(R.id.beforeprice)
    TextView yuanPrice;
    @Bind(R.id.nowprice)
    TextView nowprice;
    @Bind(R.id.webview)
    WebView webview;
    @Bind(R.id.shoucang)
    ImageView shoucang;
    @Bind(R.id.wenan)
    LinearLayout wenan;
    @Bind(R.id.upgrade)
    TextView upgrade;
    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.zhuan)
    TextView tv_zhuan;
    @Bind(R.id.name2)
    TextView name2;
    @Bind(R.id.source)
    ImageView source;
    @Bind(R.id.collection_view)
    LinearLayout collection;
    @Bind(R.id.share_view)
    LinearLayout shareView;
    @Bind(R.id.quan_view)
    LinearLayout quanView;
    @Bind(R.id.shopname)
    TextView shopname;
    @Bind(R.id.shop)
    ImageView shop;
    @Bind(R.id.quanhou_back)
    TextView quanhouBack;
    @Bind(R.id.dianpu)
    LinearLayout dianpu;
    private String collectionState;
    private SharedPreferences sp;
    private SharedPreferences.Editor editor;
    private String itemid;
    private String youhuiquan;
    private String eventRate;
    private List<String> list = new ArrayList<>();
    private String maType;
    private JDListBean jdbean;
    private String salePrice, ispingou;
    private String materialUrl;
    private String couponUrl;
    private String quanurl;
    private DecimalFormat df = new DecimalFormat("0.00");
    private DecimalFormat df1 = new DecimalFormat("0");


    @Override
    public int bindLayout() {
        return R.layout.activity_jd_detail;
    }

    @Override
    public void initView(View view) {
        sp = getSharedPreferences("user", MODE_PRIVATE);
        editor = sp.edit();
        maType = sp.getString("SpareTwo", "");
        yuanPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        title.setText("商品详情");
        CleanCacheUtil.clearAllCache(this);
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        //设置图片加载器
        banner.setImageLoader(new GlideImageLoader());
        //设置自动轮播，默认为true
        banner.isAutoPlay(true);
        //设置轮播时间
        banner.setDelayTime(5000);
        //设置指示器位置（当banner模式中有指示器时）
        banner.setIndicatorGravity(BannerConfig.CENTER);
        WebSettings webSettings = webview.getSettings();
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webview.setInitialScale(5);
        webSettings.setSupportZoom(true);
        webSettings.setBuiltInZoomControls(true);
        webSettings.setDisplayZoomControls(false);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSettings.setDomStorageEnabled(true);
        webSettings.setDatabaseEnabled(true);
        webSettings.setAppCacheEnabled(true);
        if (maType.equals("") || maType.equals("1")) {
            shareView.setVisibility(View.GONE);
        } else {
            shareView.setVisibility(View.VISIBLE);
        }
        back.setVisibility(View.VISIBLE);
        itemid = getIntent().getStringExtra("itemId");
        GetJDdetail();
        getState();
        back.setOnClickListener(this);
        lianjie.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
        lianjie.getPaint().setAntiAlias(true);//抗锯齿
        share.setOnClickListener(this);
        copy.setOnClickListener(this);
        paste.setOnClickListener(this);
        upgrade.setOnClickListener(this);
        quan.setOnClickListener(this);
        collection.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back: {
                finish();
            }
            break;
            case R.id.share: {
                if (null != quan && !youhuiquan.equals("")) {
                    Intent in = new Intent(JDProductDetailActivity.this, JDSharePictureActivity.class);
                    in.putExtra("quan", youhuiquan);
                    in.putExtra("price", salePrice);
                    in.putExtra("h5", quanurl);
                    in.putExtra("ispingou", ispingou);
                    in.putExtra("salume", salenum.getText().toString());
                    in.putExtra("title", ptitle.getText().toString());
                    in.putExtra("shop", shopname.getText().toString());
                    in.putStringArrayListExtra("imageList", (ArrayList<String>) list);
                    startActivity(in);
                }
            }
            break;
            case R.id.copy: {
                if (maType.equals("") || maType.equals("1")) {
                    dosure();
                } else {
                    toJd(quanurl);
                }
            }
            break;
            case R.id.quan: {
                if (maType.equals("") || maType.equals("1")) {
                    dosure();
                } else {
                    toJd(quanurl);
                }
            }
            break;
            case R.id.paste: {
                if (null != quanurl && !quanurl.equals("")) {
                    RegexValidateUtils.copyText(this, ptitle.getText().toString().replace("【", "").replace("】", "") + "\n" + money.getText().toString() + "\n" + nowprice.getText().toString() + "\n" + save.getText().toString() + "\n" + "点击下面的链接即可领券" + "\n" + quanurl);
                    ToastUtils.getInstance(JDProductDetailActivity.this).showMessage("复制成功");
                }
            }
            break;
            case R.id.collection_view: {
                if (null != collectionState && collectionState.equals("1")) {
                    CanceltheCollection();
                } else {
                    Collection();
                }
            }
            break;
            default:
                break;
        }
    }

    public void GetJDdetail() {
        if (!DeviceUtils.isNetworkAvalible(this)) {
            if (!isFinishing()) {
                ToastUtils.getInstance(this).showMessage("网络连接错误请检查");
            }
            return;
        }
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        HashMap<String, Object> map = new HashMap();
        map.put("skuid", itemid);
        if (null == mWeiboDialog || !mWeiboDialog.isShowing()) {
            mWeiboDialog = WeiboDialogUtils.createLoadingDialog(this);
        }
        RetrofitManager.getInstance(AppConfig.BASE_URL).createReq(RequestApi.class).Details(map, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "skuid" + itemid)).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JDListBean>() {
            @Override
            public void onCompleted() {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
            }

            @Override
            public void onError(Throwable e) {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
            }

            @Override
            public void onNext(JDListBean bean) {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
                if (bean.getCode().equals("0")) {
                    if (null == bean.getData()) {
                        commomDialog("该商品暂无佣金计划");
                        return;
                    }
                    jdbean = bean;
                    dianpu.setVisibility(View.GONE);
                    youhuiquan = bean.getData().get(0).getDiscount();
                    salePrice = df.format(Double.parseDouble(bean.getData().get(0).getWlPrice()) - Double.parseDouble(youhuiquan));
                    quan.setText(youhuiquan + "元优惠券");
                    salenum.setText("月销  " + bean.getData().get(0).getSales());
                    salenum.setVisibility(View.INVISIBLE);
                    source.setImageResource(R.mipmap.jd_source);
                    shop.setImageResource(R.mipmap.jd_shop);
                    eventRate = bean.getData().get(0).getWlCommissionShare();
                    ispingou = "yes";
                    money.setText("◆原价:" + df.format(Double.parseDouble(bean.getData().get(0).getWlPrice())) + "元");
                    yuanPrice.setText("原价:" + df.format(Double.parseDouble(bean.getData().get(0).getWlPrice())));
                    nowprice.setText("券后价:" + salePrice + "元");
                    save.setText("◆节省:" + df.format(Double.parseDouble(youhuiquan)) + "元");
                    quanhou.setText("¥" + df.format(Double.parseDouble(bean.getData().get(0).getWlPrice()) - Double.parseDouble(youhuiquan)));
                    if (maType.equals("2")) {
                        upgrade.setText("升级超级教练可享佣金￥" + df.format((Double.parseDouble(bean.getData().get(0).getWlPrice()) - Double.parseDouble(youhuiquan)) * Double.parseDouble(bean.getData().get(0).getWlCommissionShare()) / 100));
                        share.setText("分享赚\n￥" + df.format((Double.parseDouble(bean.getData().get(0).getWlPrice()) - Double.parseDouble(youhuiquan)) * Double.parseDouble(bean.getData().get(0).getWlCommissionShare()) / 200));
                        tv_zhuan.setText("  赚 ￥" + df.format((Double.parseDouble(bean.getData().get(0).getWlPrice()) - Double.parseDouble(youhuiquan)) * Double.parseDouble(bean.getData().get(0).getWlCommissionShare()) / 200));
                        ymoney.setText("佣金:" + df.format(Double.parseDouble(eventRate) / 2) + "%");
                        if (Double.parseDouble(youhuiquan) > 0) {
                            copy.setText("自买省\n" + "￥" + df1.format(Double.parseDouble(youhuiquan)) + "+￥" + df.format((Double.parseDouble(bean.getData().get(0).getWlPrice()) - Double.parseDouble(youhuiquan)) * Double.parseDouble(bean.getData().get(0).getWlCommissionShare()) / 200));
                        } else {
                            copy.setText("自买省\n" + "￥" + df.format((Double.parseDouble(bean.getData().get(0).getWlPrice()) - Double.parseDouble(youhuiquan)) * Double.parseDouble(bean.getData().get(0).getWlCommissionShare()) / 200));
                        }
                    } else {
                        share.setText("分享赚\n￥" + df.format((Double.parseDouble(bean.getData().get(0).getWlPrice()) - Double.parseDouble(youhuiquan)) * Double.parseDouble(bean.getData().get(0).getWlCommissionShare()) / 100));
                        tv_zhuan.setText("  赚 ￥" + df.format((Double.parseDouble(bean.getData().get(0).getWlPrice()) - Double.parseDouble(youhuiquan)) * Double.parseDouble(bean.getData().get(0).getWlCommissionShare()) / 100));
                        ymoney.setText("佣金:" + eventRate + "%");
                        upgrade.setVisibility(View.GONE);
                        if (Double.parseDouble(youhuiquan) > 0) {
                            copy.setText("自买省\n" + "￥" + df1.format(Double.parseDouble(youhuiquan)) + "+￥" + df.format((Double.parseDouble(bean.getData().get(0).getWlPrice()) - Double.parseDouble(youhuiquan)) * Double.parseDouble(bean.getData().get(0).getWlCommissionShare()) / 100));
                        } else {
                            copy.setText("自买省\n" + "￥" + df.format((Double.parseDouble(bean.getData().get(0).getWlPrice()) - Double.parseDouble(youhuiquan)) * Double.parseDouble(bean.getData().get(0).getWlCommissionShare()) / 100));
                        }
                    }
                } else {
                    commomDialog(bean.getMessage());
                }
                SpannableString spannableString = new SpannableString(quanhou.getText().toString());
                RelativeSizeSpan sizeSpan = new RelativeSizeSpan(1.2f);
                spannableString.setSpan(sizeSpan, 0, quanhou.getText().toString().indexOf("."), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                quanhou.setText(spannableString);
                materialUrl = "https://wqitem.jd.com/item/view?sku=" + bean.getData().get(0).getSkuId();
                couponUrl = bean.getData().get(0).getCouponList();
                GetURL();
                list.add(bean.getData().get(0).getPicUrl());
                banner.setImages(list);
                banner.start();
                if (bean.getData().get(0).getSkuName().length() >= 22) {
                    name.setText(bean.getData().get(0).getSkuName().substring(0, 22));
                    name2.setText(bean.getData().get(0).getSkuName().substring(22, bean.getData().get(0).getSkuName().length()));
                } else {
                    name.setText(bean.getData().get(0).getSkuName());
                }
                ptitle.setText(bean.getData().get(0).getSkuName());
                if (maType.equals("") || maType.equals("1")) {
                    ymoney.setVisibility(View.GONE);
                    wenan.setVisibility(View.GONE);
                    paste.setVisibility(View.GONE);
                    tv_zhuan.setVisibility(View.GONE);
                    copy.setText("自买省￥" + youhuiquan);
                    if (null != bean.getData().get(0).getWlPrice()) {
                        upgrade.setText("升级超级教练可享佣金￥" + df.format((Double.parseDouble(bean.getData().get(0).getWlPrice()) - Double.parseDouble(youhuiquan)) * Double.parseDouble(bean.getData().get(0).getWlCommissionShare()) / 100));
                    } else {
                        upgrade.setText("升级超级教练可享佣金￥" + df.format((Double.parseDouble(bean.getData().get(0).getWlPrice()) - Double.parseDouble(youhuiquan)) * Double.parseDouble(bean.getData().get(0).getWlCommissionShare()) / 100));
                    }
                    if (Integer.parseInt(youhuiquan) > 0) {
                        copy.setText("自买省" + "￥" + youhuiquan);
                    } else {
                        copy.setText("领券");
                    }
                } else {
                    tv_zhuan.setVisibility(View.VISIBLE);
                    wenan.setVisibility(View.VISIBLE);
                    paste.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    public void GetURL() {
        if (!DeviceUtils.isNetworkAvalible(this)) {
            if (!isFinishing()) {
                ToastUtils.getInstance(this).showMessage("网络连接错误请检查");
            }
            return;
        }
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        HashMap<String, Object> map = new HashMap();
        map.put("subUnionId", sp.getString("userId", ""));
        map.put("materialId", materialUrl);
        map.put("couponUrl", couponUrl);
        if (null == mWeiboDialog || !mWeiboDialog.isShowing()) {
            mWeiboDialog = WeiboDialogUtils.createLoadingDialog(this);
        }
        RetrofitManager.getInstance(AppConfig.BASE_URL).createReq(RequestApi.class).Bysubunionid(map, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "subUnionId" + sp.getString("userId", "") + "materialId" + materialUrl + "couponUrl" + couponUrl)).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
            }

            @Override
            public void onError(Throwable e) {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
            }

            @Override
            public void onNext(JSONObject obj) {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
                if (obj.getString("code").equals("0")) {
                    quanurl = obj.getString("data");
                    lianjie.setText("领券链接:" + quanurl);
                }
            }
        });
    }

    public void getState() {
        String userId = sp.getString("userId", "");
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).JdGetState(userId, itemid, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "UserId" + userId + "Goodsid" + itemid)).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(JSONObject json) {
                if (json.getString("code").equals("1")) {
                    shoucang.setImageResource(R.mipmap.sc);
                    collectionState = "1";
                } else {
                    collectionState = "-1";
                    shoucang.setImageResource(R.mipmap.sc_);
                }
            }
        });
    }

    public void CanceltheCollection() {
        String userId = sp.getString("userId", "");
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).JdCanceltheCollection(userId, itemid, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "UserId" + userId + "Goodsid" + itemid)).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(JSONObject json) {
                if (json.getString("code").equals("1")) {
                    collectionState = "-1";
                    shoucang.setImageResource(R.mipmap.sc_);
                    ToastUtils.getInstance(JDProductDetailActivity.this).showMessage("取消收藏成功");
                } else {
                    collectionState = "1";
                    shoucang.setImageResource(R.mipmap.sc);
                    ToastUtils.getInstance(JDProductDetailActivity.this).showMessage("取消收藏失败");
                }
            }
        });
    }

    public void Collection() {
        String userId = sp.getString("userId", "");
        if (null != userId && null != jdbean && null != jdbean.getData()) {
            String price = df.format(Double.parseDouble(jdbean.getData().get(0).getWlPrice()));
            getCollection(userId, list.get(0), jdbean.getData().get(0).getSkuName(), jdbean.getData().get(0).getSales() + "", price);
        }
    }

    public void getCollection(String userId, String url, String title, String volume, String price) {
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        HashMap<String, Object> map = new HashMap();
        map.put("UserId", userId);
        map.put("ItemId", itemid);
        map.put("ImgUrl", url);
        map.put("Title", title);
        map.put("OriginalPrice", price);
        map.put("PresentPrice", df.format(Double.parseDouble(price) - Double.parseDouble(youhuiquan)));
        map.put("Coupon", youhuiquan);
        map.put("Volume", volume);
        map.put("Commission", tv_zhuan.getText().toString());
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).JdCollection(map, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "ItemId" + itemid + "UserId" + userId + "ImgUrl" + url + "Title" + title + "OriginalPrice" + price + "Coupon" + youhuiquan + "Volume" + volume + "Commission" + tv_zhuan.getText().toString() + "PresentPrice" + df.format(Double.parseDouble(price) - Double.parseDouble(youhuiquan)))).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(JSONObject json) {
                if (json.get("code").equals("1")) {
                    collectionState = "1";
                    ToastUtils.getInstance(JDProductDetailActivity.this).showMessage("收藏成功");
                    shoucang.setImageResource(R.mipmap.sc);
                } else {
                    collectionState = "-1";
                    ToastUtils.getInstance(JDProductDetailActivity.this).showMessage("收藏失败");
                    shoucang.setImageResource(R.mipmap.sc_);
                }
            }
        });
    }


    @Override
    protected void onResume() {
        super.onResume();
    }


    public void dosure() {
        new CommonDialog.Builder(this)
                .setTitle("提示")
                .setMessage("此操作不可撤销，请确认余额" + youhuiquan + "元兑换此产品")
                .setPositiveButton("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        toJd(quanurl);
                    }
                })
                .setNegativeButton("取消", null).show();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mWeiboDialog) {
            mWeiboDialog.cancel();
        }
        webview.stopLoading();
        webview.getSettings().setJavaScriptEnabled(false);
        webview.clearHistory();
        webview.removeAllViews();
        webview.destroy();
    }

    public void Duihuan() {
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL).createReq(RequestApi.class).SetBuy(sp.getString("userPhone", ""), youhuiquan, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "UserPhone" + sp.getString("userPhone", "") + "Money" + youhuiquan)).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(JSONObject obj) {
                if (obj.getString("code").equals("0")) {
                    ToastUtils.getInstance(JDProductDetailActivity.this).showMessage("兑换成功");
                } else if (obj.getString("code").equals("-1")) {
                    ToastUtils.getInstance(JDProductDetailActivity.this).showMessage("兑换失败");

                } else if (obj.getString("code").equals("-2")) {
                    ToastUtils.getInstance(JDProductDetailActivity.this).showMessage("余额不足，请充值");
                }
            }
        });
    }


    public void commomDialog(String Message) {
        new CommonDialog.Builder(this)
                .setTitle("提示")
                .setMessage(Message)
                .setMessageGravity()
                .setCanceledOnTouchOutside(false)
                .setPositiveButton("我知道了", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        finish();
                    }
                }).show();
    }

    public void toJd(String url) {
        OpenAppAction mOpenAppAction = new OpenAppAction() {
            @Override
            public void onStatus(final int status, final String url) {
                if (status == OpenAppAction.OpenAppAction_start) {//开始状态未必一定执
                }
                if (status == OpenAppAction.OpenAppAction_result_NoJDAPP) {
                    ToastUtils.getInstance(JDProductDetailActivity.this).showMessage("请先安装京东");
                    //未安装京东
                } else if (status == OpenAppAction.OpenAppAction_result_BlackUrl) {
                    //不在白名单
                } else if (status == OpenAppAction.OpenAppAction_result_ErrorScheme) {
                    //协议错误
                } else if (status == OpenAppAction.OpenAppAction_result_APP) {
                    if (maType.equals("") || maType.equals("1")) {
                        Duihuan();
                    }
                    //呼京东成功
                } else if (status == OpenAppAction.OpenAppAction_result_NetError) {
                    //网络异常
                    ToastUtils.getInstance(JDProductDetailActivity.this).showMessage("网络异常,请稍后重试！");
                }
            }
        };
        KeplerAttachParameter mKeplerAttachParameter = new KeplerAttachParameter();
        KeplerApiManager.getWebViewService().openAppWebViewPage(JDProductDetailActivity.this, url,
                mKeplerAttachParameter,
                mOpenAppAction);
    }

    @Override
    public void onPause() {
        super.onPause();
        banner.stopAutoPlay();
    }

    @Override
    public void onStart() {
        super.onStart();
        banner.startAutoPlay();
    }
}
